package com.itheima.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 新增菜品
     * @param dishDto
     */
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        //1.保存菜品的基本信息到菜品表
        this.save(dishDto);
        //2.新增菜品结束之后，菜品id就已经生成，我们需要获取到菜品的id然后封装到dishDto里 去给菜品口味表中的菜品id赋值
        Long dishId = dishDto.getId();
        //3.把菜品口味的集合拿出来
        List<DishFlavor> flavors = dishDto.getFlavors();
        //4.为集合中的每一个口味附上当前菜品的id
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
        //2.保存菜品口味表
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //根据id查询出菜品的基本信息
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);

        //
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> list = dishFlavorService.list(wrapper);
        dishDto.setFlavors(list);
        return dishDto;
    }

    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //先更新菜品的基本信息
        this.updateById(dishDto);
        //清除原来的菜品口味信息
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(wrapper);
        //把新口味添加进去
        //把菜品口味的集合拿出来
        List<DishFlavor> flavors = dishDto.getFlavors();
        //为集合中的每一个口味附上当前菜品的id
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDto.getId()));
        //保存菜品口味表
        dishFlavorService.saveBatch(flavors);
    }
}
